package com.rabbit.demo.sentinelLearn;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname HelloSentinelController
 * @Description TODO
 * @Date 2021/9/12 21:45
 * @Created by ylr
 */


@RestController
@Slf4j
public class HelloSentinelController {
    private static final String resourceName = "helloSentinel";

    @GetMapping("/helloSentinel")
    public String Hello(){
        Entry entry = null;

        try {
            // 定义一个sentinel保护的资源，名称为test-sentinel-api
            entry = SphU.entry(resourceName);
            // 模拟执行被保护的业务逻辑耗时
            Thread.sleep(100);
            return "helloSentinel ok";
        } catch (BlockException e) {
            // 如果被保护的资源被限流或者降级了，就会抛出BlockException
            log.warn("资源被限流或降级了", e);
            return "资源被限流或降级了";
        } catch (InterruptedException e) {
            return "发生InterruptedException";
        } finally {
            if (entry != null) {
                entry.exit();
            }

            ContextUtil.exit();
        }

    }

    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource(resourceName);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(1);
        rules.add(flowRule);

        FlowRuleManager.loadRules(rules);


    }


}
